﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel.Composition;
using System.Windows;

namespace Dynamic_UI_Framework
{
    [Export(typeof(DockPanelLayoutAdapter))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class DockPanelLayoutAdapter : AdapterBase<ILayout, DockPanel>
    {
        protected override void Adapt(ILayout bench, DockPanel target)
        {
            bench.Target = target;
            Layout l  = bench as Layout;

            target.ContextMenu = new ContextMenu();
            foreach (var mi in l.GetMenuItem())
            {
                target.ContextMenu.Items.Add(mi);
            }

            l.Items.CollectionChanged += (s, e) => {
                foreach (var item in l.Items)
                {
                    if (target.Children.Contains(item.Target) == false)
                        target.Children.Add(item.Target);
                }
                for (int i = 0; i < target.Children.Count;i++ )
                {
                    UIElement ele = target.Children[i];
                    bool isFind = false;
                    foreach (var t in l.Items)
                    {
                        if (t.Target.Equals(ele))
                        {
                            isFind = true;
                            break;
                        }
                    }
                    if (isFind == false)
                        target.Children.Remove(ele);
                }
            };
        }

        protected override ILayout Create()
        {
            return new Layout();
        }
    }
}
